<?php

namespace App\Http\Services;

use App\Models\Enter;
use App\Models\InviteReward;
use App\Models\Product;
use App\Models\PromotBanner;
use App\Models\Setting;
use App\Models\User;
use EasyWeChat\OfficialAccount\Application;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LoginService
{

    public function enter($param)
    {
        $exist =Enter::where('mobile', $param['mobile'])->where('name', $param['name'])->first();
        if ($exist) {
            return ['code'=>0, 'msg'=>'提交信息已存在'];
        }
        Enter::create($param);
        return ['code'=>200, 'msg'=>'提交成功'];
    }

    public function product()
    {
        $list = Product::where([])->orderBy('sort', 'asc')->get();
        foreach ($list as $k => $v) {
            $list[$k]->image = env('APP_URL') . '/storage/' . $v->image;
            $list[$k]->prize = env('APP_URL') . '/storage/' . $v->prize;
            $list[$k]->questions = env('APP_URL') . '/storage/' . $v->questions;
        }
        return ['code'=>200, 'data'=>$list];
    }

    public function banners($from)
    {
        if (!in_array($from, [2, 1])) {
            $from = 1;
        }
        $list = PromotBanner::where('from', $from)->orderBy('sort')->get();
        foreach ($list as $k => $v) {
            $list[$k]->image = env('APP_URL') . '/storage/' . $v->image;
        }
        return ['code'=>200, 'data'=>$list];
    }

    public function about()
    {
        $value = Setting::where('id', 5)->value('value');
        $value = env('APP_URL') . '/storage/' . $value;
        $content = Setting::where('id', 6)->value('value');

        $address = Setting::where('id', 7)->value('value');
        return ['code'=>200, 'image'=>$value, 'content'=>$content, 'address'=>$address];
    }

    public function login($data)
    {
        $config = [
            'app_id' => config('wechat.appid'),
            'secret' => config('wechat.secret'),
            'token' => config('wechat.token'),
            'aes_key' => '', // 明文模式请勿填写 EncodingAESKey
            //ma9WLZnYPPGc8HeZkmDEHWiHcFWIhSPrJSpHrzB0uUB
        ];

        $app = new Application($config);
        $oauth = $app->getOauth();
        $userinfo = $oauth->userFromCode($data['code']);

        $user = User::where('openid', $userinfo->getId())->first();
        if (!$user){
            DB::beginTransaction();
            try {
                $user = new User();
                $user->pid = $data["pid"] ?? 0;
                $user->openid = $userinfo->getId();
                $user->name = $userinfo->getNickname();
                $user->avatar = $userinfo->getAvatar();
                $user->sex = $userinfo->getRaw()['sex'] ?? 0;
                $user->save();

                if ($user->pid) {
                    $pUser = User::where('id', $user->pid)->where('is_invite', 1)->first();
                    if ($pUser) {
                        $directReward = Setting::where('id', 3)->value('value');
                        $dIRD = [
                            'uid' => $pUser->id,
                            'from_id' => $user->id,
                            'money' => $directReward,
                        ];
                        InviteReward::create($dIRD);
                        $pUser->balance += $directReward;
                        $pUser->save();

                        if ($pUser->pid){
                            $ppUser = User::where('id', $pUser->pid)->where('is_invite', 1)->first();
                            if ($ppUser) {
                                $indirectReward = Setting::where('id', 4)->value('value');
                                $iIRD = [
                                    'uid' => $ppUser->id,
                                    'from_id' => $user->id,
                                    'money' => $indirectReward,
                                ];
                                InviteReward::create($iIRD);
                                $ppUser->balance += $directReward;
                                $ppUser->save();
                            }
                        }
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                Log::error('登录失败');
                Log::error($e->getMessage(), $e->getTrace());
                return ['code'=>0, 'msg'=>"登录失败"];
            }
        }
        $token = $user->createToken('web')->plainTextToken;
        return ['code'=>200, 'msg'=>"成功", 'token'=>$token];
    }
}
